<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Default controller.
 */
class Block_Controller extends Template_Controller 
{
	public function __construct()
	{
		parent::__construct();
		
		// Add the menu to the template
		$this->template->menu = new View('menu');
		$this->template->content = '';
	}
	
	public function index()
	{
		self::lists(1);
	}

	public function lists($block_id, $page_no)
	{
		$page_size = 20;
	    $block = new Block_Model();
		$element = new Block_Element_Model();
		
		$this->pagination = new Pagination(array(
	        'base_url'    => 'block/lists/', 
	        'uri_segment' => 3, 
			'items_per_page' => $page_size, 
	        'total_items' => $block->select('COUNT(*) AS records_found')->find()->records_found
	    ));
	 
		$table = new View('block/lists');
		$table->datas = $block->limit($page_size, (($page_no - 1) * $page_size))->find_all();
		
		if($block_id == 0)
		{
			$table->block = $block->limit(1)->find();
		}
		else
		{
			$table->block = $block->find($block_id);
		}
		
		$table->elements = $element->select('*, block_elements.id as eid')
								->join($block->source_name, 'block_elements.source_pk_id='.$block->source_name.'.id')
							    ->where('block_elements.block_id', $block->id)
								->orderby('sort', 'asc')
								->find_all();
								
		$this->template->content = $table->render();
	}
	
	public function addpkid($block_id)
	{
		if($_POST['pkid'])
		{
			$block = new Block_Model($block_id);
			$object = ORM::factory(inflector::singular($block->source_name))->find($_POST['pkid']);
			
			if($object->id)
			{
				$element = new Block_Element_Model();
				$has = $element->where('block_id', $block_id)
							   ->where('source_pk_id', $object->id)->find();
				if ( ! $has->id )
				{
					$element = new Block_Element_Model();
					$element->block_id = $block_id;
					$element->source_pk_id = $object->id;
					$element->save();
				}
			}
		}
		
		url::redirect('block/lists/'.$block_id.'/1', 301);
	}
	
	public function delpkid($block_id, $element_id)
	{
		$element = new Block_Element_Model($element_id);
		$element->delete();
		
		url::redirect('block/lists/'.$block_id.'/1', 301);
	}
	
	public function update($block_id)
	{
		if(is_array($_POST['ids']))
		{
			foreach($_POST['ids'] as $eid)
			{
				$element = new Block_Element_Model($eid);
				$element->url_link = $_POST['link_'.$eid];
				$element->sort = $_POST['sort_'.$eid];
				$element->save();
			}
		}
		
		url::redirect('block/lists/'.$block_id.'/1', 301);
	}
}